<template>
  <div class="annual-report">
    <h1>国家大学科技园年度报表</h1>
    <el-form :model="form" :rules="formRules" label-width="180px" ref="ruleFormRef" style="max-width: 1200px; width: 100%">
      <!-- 基本信息 -->
      <el-card>
        <div slot="header" class="header">基本信息</div>
        <el-form-item label="企业名称" prop="enterpriseName">
          <el-input v-model="form.enterpriseName" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="creditCode">
          <el-input v-model="form.creditCode" placeholder="请输入统一社会信用代码" />
        </el-form-item>
        <el-form-item label="是否高新技术企业" prop="isHightechEnterprise">
          <el-radio-group v-model="form.isHightechEnterprise">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item 
          v-if="form.isHightechEnterprise === 1" 
          label="证书编号" 
          prop="highTechCertificateNo"
          :rules="formRules.highTechCertificateNo"
        >
          <el-input v-model="form.highTechCertificateNo" placeholder="请输入高新技术企业证书编号" />
        </el-form-item>
        <el-form-item label="是否科技型中小企业" prop="isTechSmallMedium">
          <el-radio-group v-model="form.isTechSmallMedium">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item 
          v-if="form.isTechSmallMedium === 1" 
          label="登记编码" 
          prop="techSmeRegistrationCode"
          :rules="formRules.techSmeRegistrationCode"
        >
          <el-input v-model="form.techSmeRegistrationCode" placeholder="请输入科技型中小企业登记编码" />
        </el-form-item>
        <el-form-item label="是否创新型中小企业" prop="isInnovativeSme">
          <el-radio-group v-model="form.isInnovativeSme">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否专精特新中小企业" prop="isSpecializedRefinedSme">
          <el-radio-group v-model="form.isSpecializedRefinedSme">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否专精特新小巨人企业" prop="isLittleGiantEnterprise">
          <el-radio-group v-model="form.isLittleGiantEnterprise">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-card>

      <!-- 经济概况 -->
      <el-card>
        <div slot="header" class="header">在孵企业经济概况</div>
        <el-form-item label="在孵企业总收入（千元）" prop="totalIncome">
          <el-input-number v-model="form.totalIncome" :min="0" placeholder="请输入在孵企业总收入" />
        </el-form-item>
        <el-form-item label="在孵企业工业总产值（千元）" prop="industrialOutput">
          <el-input-number v-model="form.industrialOutput" :min="0" placeholder="请输入在孵企业工业总产值" />
        </el-form-item>
        <el-form-item label="在孵企业净利润（千元）" prop="netProfit">
          <el-input-number v-model="form.netProfit" :min="0" placeholder="请输入在孵企业净利润" />
        </el-form-item>
        <el-form-item label="在孵企业上缴税额（千元）" prop="taxPayment">
          <el-input-number v-model="form.taxPayment" :min="0" placeholder="请输入在孵企业上缴税额" />
        </el-form-item>
        <el-form-item label="在孵企业出口总额（千元）" prop="exportVolume">
          <el-input-number v-model="form.exportVolume" :min="0" placeholder="请输入在孵企业出口总额" />
        </el-form-item>
      </el-card>

      <!-- 知识产权情况 -->
      <el-card>
        <div slot="header" class="header">在孵企业知识产权情况</div>
        <el-form-item label="专利申请数（件）" prop="patentApplication">
          <el-input-number v-model="form.patentApplication" :min="0" placeholder="请输入专利申请数" />
        </el-form-item>
        <el-form-item label="其中：发明专利（件）" prop="inventionPatentApplication">
          <el-input-number v-model="form.inventionPatentApplication" :min="0" placeholder="请输入发明专利申请数" />
        </el-form-item>
        <el-form-item label="专利授权数（件）" prop="patentGranted">
          <el-input-number v-model="form.patentGranted" :min="0" placeholder="请输入专利授权数" />
        </el-form-item>
        <el-form-item label="其中：发明专利（件）" prop="inventionPatentGranted">
          <el-input-number v-model="form.inventionPatentGranted" :min="0" placeholder="请输入发明专利授权数" />
        </el-form-item>
      </el-card>

      <!-- 从业人员情况 -->
      <el-card>
        <div slot="header" class="header">在孵企业从业人员情况</div>
        <el-form-item label="在孵企业从业人员（人）" prop="employees">
          <el-input-number v-model="form.employees" :min="0" placeholder="请输入在孵企业从业人员数" />
        </el-form-item>
        <el-form-item label="其中：博士（人）" prop="doctorNum">
          <el-input-number v-model="form.doctorNum" :min="0" placeholder="请输入博士人数" />
        </el-form-item>
        <el-form-item label="硕士（人）" prop="masterNum">
          <el-input-number v-model="form.masterNum" :min="0" placeholder="请输入硕士人数" />
        </el-form-item>
        <el-form-item label="研究生学历（人）" prop="postgraduateNum">
          <el-input-number v-model="form.postgraduateNum" :min="0" placeholder="请输入研究生学历人数" />
        </el-form-item>
        <el-form-item label="本科学历（人）" prop="bachelorNum">
          <el-input-number v-model="form.bachelorNum" :min="0" placeholder="请输入本科学历人数" />
        </el-form-item>
        <el-form-item label="大专学历（人）" prop="collegeNum">
          <el-input-number v-model="form.collegeNum" :min="0" placeholder="请输入大专学历人数" />
        </el-form-item>
        <el-form-item label="中专学历（人）" prop="technicalSchoolNum">
          <el-input-number v-model="form.technicalSchoolNum" :min="0" placeholder="请输入中专学历人数" />
        </el-form-item>
        <el-form-item label="研究开发人员（人）" prop="rdPersonnel">
          <el-input-number v-model="form.rdPersonnel" :min="0" placeholder="请输入研究开发人员数" />
        </el-form-item>
        <el-form-item label="研究与试验发展（R&D）人员（人）" prop="rdPersonnelDetail">
          <el-input-number v-model="form.rdPersonnelDetail" :min="0" placeholder="请输入研究与试验发展（R&D）人员数" />
        </el-form-item>
        <el-form-item label="留学回国人员（人）" prop="returnee">
          <el-input-number v-model="form.returnee" :min="0" placeholder="请输入留学回国人员数" />
        </el-form-item>
        <el-form-item label="接纳大学生、研究生实习人员（人）" prop="internAcceptance">
          <el-input-number v-model="form.internAcceptance" :min="0" placeholder="请输入接纳大学生、研究生实习人员数" />
        </el-form-item>
        <el-form-item label="接纳应届毕业生就业人员（人）" prop="freshGraduateEmployment">
          <el-input-number v-model="form.freshGraduateEmployment" :min="0" placeholder="请输入接纳应届毕业生就业人员数" />
        </el-form-item>
      </el-card>

      <!-- 科技活动情况 -->
      <el-card>
        <div slot="header" class="header">在孵企业科技活动情况</div>
        <el-form-item label="承担各级各类科技计划项目（项）" prop="techProjectTotal">
          <el-input-number v-model="form.techProjectTotal" :min="0" placeholder="请输入承担科技计划项目数" />
        </el-form-item>
        <el-form-item label="其中：国家级项目（项）" prop="nationalTechProject">
          <el-input-number v-model="form.nationalTechProject" :min="0" placeholder="请输入国家级项目数" />
        </el-form-item>
        <el-form-item label="研究开发经费支出总额（千元）" prop="rdExpenditureTotal">
          <el-input-number v-model="form.rdExpenditureTotal" :min="0" placeholder="请输入研究开发经费支出总额" />
        </el-form-item>
        <el-form-item label="研究与试验发展（R&D）经费支出（千元）" prop="rdExpenditure">
          <el-input-number v-model="form.rdExpenditure" :min="0" placeholder="请输入研究与试验发展（R&D）经费支出" />
        </el-form-item>
        <el-form-item label="新产品开发经费支出（千元）" prop="newProductDevExpenditure">
          <el-input-number v-model="form.newProductDevExpenditure" :min="0" placeholder="请输入新产品开发经费支出" />
        </el-form-item>
      </el-card>

<!--      &lt;!&ndash; 填报信息 &ndash;&gt;-->
<!--      <el-card>-->
<!--        <div slot="header" class="header">填报信息</div>-->
<!--        <el-form-item label="单位详细名称" prop="companyName">-->
<!--          <el-input v-model="form.companyName" placeholder="请输入单位详细名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="单位负责人" prop="companyPrincipal">-->
<!--          <el-input v-model="form.companyPrincipal" placeholder="请输入单位负责人姓名" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="统计负责人" prop="statisticsPrincipal">-->
<!--          <el-input v-model="form.statisticsPrincipal" placeholder="请输入统计负责人姓名" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="填表人" prop="filler">-->
<!--          <el-input v-model="form.filler" placeholder="请输入填表人姓名" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="联系电话" prop="contactPhone">-->
<!--          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="报出日期" prop="reportDate">-->
<!--          <el-date-picker v-model="form.reportDate" type="date" placeholder="选择报出日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />-->
<!--        </el-form-item>-->
<!--      </el-card>-->

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="saveDraft">保存草稿</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { GetUserDataSCience, AddDataSCience, UpdataUserDataSCience,GetDataSCienceByid } from '@/api/enterpeise';
import { getLoginUserId } from '@/utils/storage';
import { useRoute } from 'vue-router';
import router from "@/router";

const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const isSubmit = ref(false);
const totalRecord = ref(0);//用来标记用户是不是第一次提交 0，1表示是从我的数据填报中点击编辑过来的
// 表单数据
const form = reactive({
  userId: getLoginUserId(), // 自动填充当前登录用户ID
  status: 0, // 默认状态为保存
  enterpriseName: '',
  creditCode: '',
  isHightechEnterprise: 0,
  highTechCertificateNo: '',
  isTechSmallMedium: 0,
  techSmeRegistrationCode: '',
  isInnovativeSme: 0,
  isSpecializedRefinedSme: 0,
  isLittleGiantEnterprise: 0,
  totalIncome: 0,
  industrialOutput: 0,
  netProfit: 0,
  taxPayment: 0,
  exportVolume: 0,
  patentApplication: 0,
  inventionPatentApplication: 0,
  patentGranted: 0,
  inventionPatentGranted: 0,
  employees: 0,
  doctorNum: 0,
  masterNum: 0,
  postgraduateNum: 0,
  bachelorNum: 0,
  collegeNum: 0,
  technicalSchoolNum: 0,
  rdPersonnel: 0,
  rdPersonnelDetail: 0,
  returnee: 0,
  internAcceptance: 0,
  freshGraduateEmployment: 0,
  techProjectTotal: 0,
  nationalTechProject: 0,
  rdExpenditureTotal: 0,
  rdExpenditure: 0,
  newProductDevExpenditure: 0,
  companyName: '',
  companyPrincipal: '',
  statisticsPrincipal: '',
  filler: '',
  contactPhone: '',
  reportDate: ''
});


// 表单验证规则
const formRules = reactive<FormRules>({
  enterpriseName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  creditCode: [{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' }],
  isHightechEnterprise: [{ required: true, message: '请选择是否高新技术企业', trigger: 'change' }],
  highTechCertificateNo: [{
    required: true,
    message: '请输入高新技术企业证书编号',
    trigger: 'blur'
  }, {
    validator: (rule: any, value: string, callback: any) => {
      if (form.isHightechEnterprise === 1 && !value) {
        callback(new Error('请选择"是"时必须填写证书编号'));
      } else {
        callback();
      }
    },
    trigger: 'blur'
  }],
  isTechSmallMedium: [{ required: true, message: '请选择是否科技型中小企业', trigger: 'change' }],
  techSmeRegistrationCode: [{
    required: true,
    message: '请输入科技型中小企业登记编码',
    trigger: 'blur'
  }, {
    validator: (rule: any, value: string, callback: any) => {
      if (form.isTechSmallMedium === 1 && !value) {
        callback(new Error('请选择"是"时必须填写登记编码'));
      } else {
        callback();
      }
    },
    trigger: 'blur'
  }],
  isInnovativeSme: [{ required: true, message: '请选择是否创新型中小企业', trigger: 'change' }],
  isSpecializedRefinedSme: [{ required: true, message: '请选择是否专精特新中小企业', trigger: 'change' }],
  isLittleGiantEnterprise: [{ required: true, message: '请选择是否专精特新小巨人企业', trigger: 'change' }],
  totalIncome: [{ type: 'number', required: true, message: '请输入在孵企业总收入', trigger: 'blur' }],
  industrialOutput: [{ type: 'number', required: true, message: '请输入在孵企业工业总产值', trigger: 'blur' }],
  netProfit: [{ type: 'number', required: true, message: '请输入在孵企业净利润', trigger: 'blur' }],
  taxPayment: [{ type: 'number', required: true, message: '请输入在孵企业上缴税额', trigger: 'blur' }],
  exportVolume: [{ type: 'number', required: true, message: '请输入在孵企业出口总额', trigger: 'blur' }],
  patentApplication: [{ type: 'number', required: true, message: '请输入专利申请数', trigger: 'blur' }],
  inventionPatentApplication: [{ type: 'number', required: true, message: '请输入发明专利申请数', trigger: 'blur' }],
  patentGranted: [{ type: 'number', required: true, message: '请输入专利授权数', trigger: 'blur' }],
  inventionPatentGranted: [{ type: 'number', required: true, message: '请输入发明专利授权数', trigger: 'blur' }],
  employees: [{ type: 'number', required: true, message: '请输入在孵企业从业人员数', trigger: 'blur' }],
  doctorNum: [{ type: 'number', required: true, message: '请输入博士人数', trigger: 'blur' }],
  masterNum: [{ type: 'number', required: true, message: '请输入硕士人数', trigger: 'blur' }],
  postgraduateNum: [{ type: 'number', required: true, message: '请输入研究生学历人数', trigger: 'blur' }],
  bachelorNum: [{ type: 'number', required: true, message: '请输入本科学历人数', trigger: 'blur' }],
  collegeNum: [{ type: 'number', required: true, message: '请输入大专学历人数', trigger: 'blur' }],
  technicalSchoolNum: [{ type: 'number', required: true, message: '请输入中专学历人数', trigger: 'blur' }],
  rdPersonnel: [{ type: 'number', required: true, message: '请输入研究开发人员数', trigger: 'blur' }],
  rdPersonnelDetail: [{ type: 'number', required: true, message: '请输入研究与试验发展（R&D）人员数', trigger: 'blur' }],
  returnee: [{ type: 'number', required: true, message: '请输入留学回国人员数', trigger: 'blur' }],
  internAcceptance: [{ type: 'number', required: true, message: '请输入接纳大学生、研究生实习人员数', trigger: 'blur' }],
  freshGraduateEmployment: [{ type: 'number', required: true, message: '请输入接纳应届毕业生就业人员数', trigger: 'blur' }],
  techProjectTotal: [{ type: 'number', required: true, message: '请输入承担科技计划项目数', trigger: 'blur' }],
  nationalTechProject: [{ type: 'number', required: true, message: '请输入国家级项目数', trigger: 'blur' }],
  rdExpenditureTotal: [{ type: 'number', required: true, message: '请输入研究开发经费支出总额', trigger: 'blur' }],
  rdExpenditure: [{ type: 'number', required: true, message: '请输入研究与试验发展（R&D）经费支出', trigger: 'blur' }],
  newProductDevExpenditure: [{ type: 'number', required: true, message: '请输入新产品开发经费支出', trigger: 'blur' }],
  companyName: [{ required: true, message: '请输入单位详细名称', trigger: 'blur' }],
  companyPrincipal: [{ required: true, message: '请输入单位负责人姓名', trigger: 'blur' }],
  statisticsPrincipal: [{ required: true, message: '请输入统计负责人姓名', trigger: 'blur' }],
  filler: [{ required: true, message: '请输入填表人姓名', trigger: 'blur' }],
  contactPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  reportDate: [{ required: true, message: '请选择报出日期', trigger: 'change' }]
});
// 初始化

// 获取用户未提交的报表数据
const getUserDraft = async (id: number)=> {
  try{
    const res = await GetDataSCienceByid(id);
    if (res.code === 200) {
        Object.assign(form, res.data);
    }
  } catch (error) {
    console.error('获取报表数据失败:', error);
    ElMessage.error('获取报表数据失败');
  }
};
// 提交表单
const submitForm = async () => {
  if (!ruleFormRef.value) return;

  form.status = 1; // 设置状态为提交

  await ruleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        let response;
        if (totalRecord.value === 1) {
          // 如果存在未提交记录,并且是从我的数据填报点击过来的，则调用更新接口
          response = await UpdataUserDataSCience(form);
        } else {
          // 否则调用添加接口
          response = await AddDataSCience(form);
        }

        if (response.code === 200) {
          ElMessage.success('提交成功');
          isSubmit.value = true;
          router.push(`/personal-center/fill-information/my-datafrom`);
        }
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败');
      }
    }else{
      ElMessage.warning('表单没有填写完整');
    }

  });
};

// 保存草稿
const saveDraft = async () => {
  if (!ruleFormRef.value) return;

  form.status = 0; // 设置状态为保存

  try {
    let response;
    if (totalRecord.value === 1) {
      // 如果存在未提交记录，则调用更新接口
      response = await UpdataUserDataSCience(form);
    } else {
      // 否则调用添加接口
      response = await AddDataSCience(form);
    }

    if (response.code === 200) {
      ElMessage.success('草稿保存成功');
      isSubmit.value = false;
      router.push(`/personal-center/fill-information/my-datafrom`);
    } else {
      ElMessage.error('保存失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败');
  }
};

// 重置表单
const resetForm = () => {
  ruleFormRef.value?.resetFields();
  isSubmit.value = false;
};

onMounted(() => {
  const id = route.query.id;
  if (id) {
    totalRecord.value=1;
    getUserDraft(Number(id)); // 页面加载时获取需要的报表数据
  }

});

</script>

<style lang="scss" scoped>
.header {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 20px;
}
.el-card {
  margin: 20px auto;
}
.annual-report {
  width: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-weight: bold;

  :deep(.el-form-item__label) {
    font-weight: bold;
  }

  :deep(.el-table th, .el-table td) {
    font-weight: bold;
  }
}
</style>